package com.example.miniofenpian.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.example.miniofenpian.config.OssConfig;
import com.example.miniofenpian.util.AmazonS3Util;
import com.example.miniofenpian.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fulin
 * @since 2024/9/19 17:17
 */
@Service
@Slf4j
public class OSSInitService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostConstruct
    public void init() {
        AmazonS3Util.clear();
        // 模拟从数据库获取数据
        List<OssConfig> ossConfigList = getList();

        // 数据库的数据不需要这么做
        String qiehuan = SpringUtil.getBean(StringRedisTemplate.class).opsForValue().get("qiehuan");
        if (StrUtil.isNotBlank(qiehuan)) {
            ossConfigList.forEach(ossConfig -> ossConfig.setStatus("0"));
            OssConfig ossConfig1 = ossConfigList.stream().filter(ossConfig -> ossConfig.getConfigKey().equalsIgnoreCase(qiehuan)).findFirst().get();
            ossConfig1.setStatus("1");
        }
        // 数据库的数据不需要这么做

        List<OssConfig> configList = ossConfigList.stream().filter(ossConfig -> ossConfig.getStatus().equals("1"))
                .collect(Collectors.toList());
        Assert.isTrue(configList.size() == 1, "OSS配置信息错误");
        OssConfig ossConfig = configList.get(0);
        // 缓存配置信息
        redisTemplate.opsForValue().set(Constant.OSS_CONFIG_KEY, ossConfig.getConfigKey());
        for (OssConfig config : ossConfigList) {
            redisTemplate.opsForValue().set(Constant.OSS_CONFIG_PROPERTIES + StrUtil.COLON + config.getConfigKey(), JSONUtil.toJsonStr(config));
        }
        log.info("初始化配置信息成功:{}", JSONUtil.toJsonStr(ossConfig));
    }

    public List<OssConfig> getList() {
        List<OssConfig> ossConfigList = new ArrayList<>();
        ossConfigList.add(new OssConfig(Constant.OSSType.MINIO.name(), "minioadmin", "minioadmin", "test", "", "192.168.1.133:9000", "", "", "", "0", "", "", "1"));
        ossConfigList.add(new OssConfig(Constant.OSSType.LOCAL.name(), "local", "local", "local", "", "localhost:8080", "", "N", "", "1", "", "", "1"));
        return ossConfigList;
    }
}
